package com.lzx.iteam.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
import com.lzx.iteam.*;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by shijunting on 15-4-23.
 * <p/>
 * 自定义接收器
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */

public class JpushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private Context mContext;
    private String sid;
    private String mPushType;//01:审批  02：考勤  03：事件  04：日程
    private String mApprovalId;
    private String mUid;
    private String mGroupId;
    private String mWeeklyId;
    private String mGroupName;

    private final int MSG_SET_REGISTRATION_ID = 1000;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SET_REGISTRATION_ID:
                    break;
            }
        }
    };


    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[JpushReceiver]" + intent.getAction() + ", extras: " + printBundle(bundle));
        // TODO 收到推送 和 点开推送通知 都会走onReceive方法
        if (!JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            try {
                JSONObject pushData = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                if (pushData.has("push_type")) {
                    String type = pushData.getString("push_type");
                    if (!"02".equals(type)) {
                        int systemCount = PreferenceUtil.getInstance(mContext).getInt("system_un_read", 0);
                        PreferenceUtil.getInstance(mContext).save("system_un_read", systemCount + 1);
                       /* MainActivity.mActivity.initChatGroupUnRead();*/
                    }
                }
                if (!JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!StringUtil.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
            Log.d(TAG, "[JpushReceiver]接收到的EXTRA_EXTRA" + bundle.getString(JPushInterface.EXTRA_EXTRA));
        }
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[JpushReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
            if (!StringUtil.isEmpty(regId)) {
                setRegistrationId(regId);
            }


        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[JpushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//            processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[JpushReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[JpushReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[JpushReceiver] 用户点击打开了通知");
            try {
                JSONObject jsonObject = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                if (!JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                }
                if (jsonObject.has("push_type")) {
                    mPushType = jsonObject.getString("push_type");
                    Log.d(TAG, " push_type : " + mPushType);
                    if ("01".equals(mPushType)) {
                        mApprovalId = jsonObject.getString("_id");
                        mUid = jsonObject.getString("approve_admin");
                    } else if ("02".equals(mPushType)) {
                        mGroupId = jsonObject.getString("group_id");
                        mGroupName = jsonObject.getString("group_name");
                    } else if ("03".equals(mPushType)) {

                    } else if ("04".equals(mPushType)) {

                    } else if ("05".equals(mPushType)) {
                        mGroupId = jsonObject.getString("group_id");
                        mWeeklyId=jsonObject.getString("weekly_id");
                    }
                }
            } catch (Exception e) {
                Log.d(TAG, " push_type : " + e.toString());
                e.printStackTrace();
            }

            Log.d(TAG, " push_type open : " + mPushType);
            Intent turnIntent = new Intent();
            if (!StringUtil.isEmpty(mPushType)) {
                if ("01".equals(mPushType)) {
                    turnIntent.setClass(context, ApprovalDetailActivity.class);
                    turnIntent.putExtra("approval_id", mApprovalId);
//                    turnIntent.putExtra("user_id", mUid);
                    turnIntent.setAction("my_receiver");
                } else if ("02".equals(mPushType)) {
                    turnIntent.setClass(context, AttendanceMainActivity.class);
                    turnIntent.putExtra("groupId", mGroupId);
                    turnIntent.putExtra("groupName", mGroupName);
                    turnIntent.setAction("my_receiver");
                } else if ("03".equals(mPushType)) {
                    turnIntent.setClass(context, MainActivity.class);
                } else if ("04".equals(mPushType)) {
                    turnIntent.setClass(context, ScheduleCalendarActivity.class);
                } else if ("05".equals(mPushType)) {
                    turnIntent.setClass(context, WeeklyDetailActivity.class);
                    turnIntent.putExtra("weeklyId",mWeeklyId);
                    turnIntent.putExtra("groupId", mGroupId);
                }
            } else {
                turnIntent.setClass(context, MainActivity.class);
            }
            LocalLogin.getInstance().login(mContext);
            //     JPushInterface.clearAllNotifications(mContext);//清除所有通知
            turnIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(turnIntent);

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[JpushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[JpushReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.d(TAG, "[JpushReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

//    //send msg to MainActivity
//    private void processCustomMessage(Context context, Bundle bundle) {
//        if (CloudDialerActivity.isForeground) {
//            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//            Intent msgIntent = new Intent(CloudDialerActivity.MESSAGE_RECEIVED_ACTION);
//            msgIntent.putExtra(CloudDialerActivity.KEY_MESSAGE, message);
//            if (!ExampleUtil.isEmpty(extras)) {
//                try {
//                    JSONObject extraJson = new JSONObject(extras);
//                    if (null != extraJson && extraJson.length() > 0) {
//                        msgIntent.putExtra(CloudDialerActivity.KEY_EXTRAS, extras);
//                    }
//                } catch (JSONException e) {
//
//                }
//
//            }
//            context.sendBroadcast(msgIntent);
//        }
//    }


    private void setRegistrationId(String registrationId) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair("registration_id", registrationId));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_SET_REGISTRATION_ID));
        message.mApi = AsynHttpClient.API_APP_ANDROID_PUSH;
        message.mParams = mList;
        AsynHttpClient.getInstance(mContext).execUserHttp(message);

    }


}
